<script lang="ts">
import {defineComponent, PropType} from "vue"
import {CloneData} from "@/units/tool";
import {ElMessage} from "element-plus";

export default defineComponent({
  name: "KeyValue",
  emits: ['update:modelValue', 'change'],
  props: {
    modelValue: {
      type: Array as PropType<Array<{ key: string, value: string }>>,
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    maxlength: {
      type: Number,
      default: 250
    },
    limit: {
      type: Number,
      default: 15
    },
    keyPlaceholder: {
      type: String,
      default: ''
    },
    valPlaceholder: {
      type: String,
      default: ''
    }
  },
  setup(props) {

    function increase() {
      if (props.modelValue.length < this.limit) {
        let data = CloneData(props.modelValue)
        data.push({key: '', value: ''})
        setValue(data)
      } else {
        ElMessage.error(`最多最能添加${props.limit}个`)
      }
    }

    function removeValue(index: number) {
      let data = CloneData(props.modelValue)
      if (data.length > 0) {
        data.splice(index, 1)
      }
      setValue(data)
    }

    /**
     * 设置表单值
     * @param value
     */
    function setValue(value: { key: string, value: string }[]) {
      this.$emit('change', value)
      this.$emit('update:modelValue', value)
    }

    return {
      increase, removeValue, setValue
    }
  }
})
</script>

<template>
  <div style="width: 100%;">
    <template v-if="modelValue.length===0">
      <el-button @click="increase" long>
        <app-icon color="#0580ff" name="Plus"></app-icon>
      </el-button>
    </template>
    <template v-else>
      <el-table :data="modelValue">
        <template #default>
          <el-table-column prop="key">
            <template #default="{ $index,row }">
              <el-input :placeholder="keyPlaceholder" maxlength="100" :disabled="disabled" v-model="row.key"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="value">
            <template #default="{ $index,row }">
              <el-input :placeholder="valPlaceholder" maxlength="100" :disabled="disabled" v-model="row.value"></el-input>
            </template>
          </el-table-column>
          <el-table-column :width="40">
            <template v-if="!disabled" #default="{ $index }">
              <app-icon name="DeleteFilled" @click="removeValue($index)" class="app-tap" color="#ff0000"></app-icon>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div class="app-padding-10" v-if="!disabled">
        <el-button type="primary" @click="increase" long>新增 +</el-button>
      </div>
    </template>
  </div>
</template>